package com.test.information.maneger.demo.dao;

import com.mongodb.client.result.UpdateResult;
import com.test.information.maneger.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class UserMogDao {
    @Autowired(required = false)
    private MongoTemplate mongoTemplate;

    public void saveUser(User user){
        //新增数据
        mongoTemplate.save(user);
    }
    public List<User> findAll()
    {
      return  mongoTemplate.findAll(User.class);
    }
    public void removeUser(int id){
        //删除数据
        Query query=new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,User.class);
    }
    public User findUserById(int id){
        Query query=new Query(Criteria.where("id").is(id));
        User user =mongoTemplate.findOne(query,User.class);
        return user;
    }
    public User findUserByName(String name){
        //通过名字查找数据
        Query query=new Query(Criteria.where("name").is(name));
        User user =mongoTemplate.findOne(query,User.class);
        return user;
    }
    public int updateUser(User user){
        //修改数据
        Query query=new Query(Criteria.where("id").is(user.getId()));
        Update update=new Update().set("name",user.getName()).set("password",user.getPassword())
                .set("age",user.getAge());
        //更新查询返回的结果集的第一条数据
        UpdateResult result = mongoTemplate.updateFirst(query,update,User.class);
        //更新查询到的所有结果集
        //UpdateResult all_result = mongoTemplate.updateMulti(query,update,User.class);
        if(result!= null)
            return (int) result.getModifiedCount();
        else
            return 0;
    }


}
